#include "fsm_thread.h"
#include "fsm_msg.h"
#include "fsm_timer.h"

#define system_msg_cnt    8
#define system_msg_size   4
static uint8_t system_msg_pool[system_msg_cnt * system_msg_size] = {0};

static fsm_msg_t fsm_msg_defunct;
static fsm_thread_t fsm_thread_defunct;
static fsm_thread_t *fsm_current_thread = 0;

/**************** 默认线程 ***********************/
void fsm_timer_msg(uint32_t addr)
{
    fsm_msg_write(&fsm_msg_defunct, (uint8_t *)&addr, system_msg_size);
}

void fsm_system_thread(void)
{
    uint32_t buf = {0};
    timer_func Appaddr = 0;
    
    if (fsm_msg_read(&fsm_msg_defunct, (uint8_t *)&buf) != 0)
    {
        Appaddr = (timer_func)buf;
        if (Appaddr) {
            Appaddr();
        }
    }
}

/*************************************  事件函数  *********************************/
void fsm_thread_init(fsm_thread_t *thread, thread_func entry)
{
    // 初始化链表
    rt_list_init(&thread->tlist);

    rt_list_insert_before(&fsm_thread_defunct.tlist, &thread->tlist);

    // 回调函数
    thread->entry = entry;
}

void fsm_system_thread_init(void)
{
    // 初始化 消息队列
    fsm_msg_init(&fsm_msg_defunct, system_msg_pool, system_msg_cnt, system_msg_size);
    fsm_thread_init(&fsm_thread_defunct, fsm_system_thread);
}

void fsm_thread_tasks(void)
{
    rt_list_t *list = &fsm_thread_defunct.tlist;

    while (1)
    {
        fsm_current_thread = rt_list_entry(list, fsm_thread_t, tlist);

        (*fsm_current_thread->entry)();

        // 下一个节点
        list = list->next;
    }
}
